import api from '@/store/api';

export const useSystemLogStore = defineStore('SystemLog', () => {
  const download = async ({ dataType, fileName }: any) => {
    const params = {
      DiagnosticDataType: 'OEM',
      OEMDiagnosticDataType: dataType,
    };
    return await api
      .post(
        '/redfish/v1/Systems/system/LogServices/HostLogger/Actions/LogService.CollectDiagnosticData',
        params,
      )
      .then((response) => {
        const disposition = response.headers['content-disposition'];
        const regex = /filename="(.*?)"/;
        const match = disposition.match(regex);
        const downloadName = match ? match[1] : `${fileName}.tar`;
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', downloadName);
        document.body.appendChild(link);
        link.click();
        link.parentNode?.removeChild(link);
        return 'Success';
      })
      .catch(() => {
        throw new Error('Failed');
      });
  };

  return { download };
});
